package com.elock.intf.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.ExceptionUtil;
import com.elock.entity.Terminal;

/**
 * Dao - 终端设备
 * @author 仁德
 */
@Repository("intfTerminalDao")
public class IntfTerminalDao extends DaoCenter {

	public Page<Map<String, Object>> findPage(Pageable pageable, Object[] args) {

		List<Object> list = new ArrayList<Object>();

		String companyCode = (String) args[0];
		String terminalNum = (String) args[1];
		String terminalName = (String) args[2];
		String saleOrgSn = (String) args[3];
		String sim = (String) args[4];

		StringBuilder sql = new StringBuilder();
		sql.append(
				"select t.*,so.name sale_org_name,sdt.value type_value,sdm.value model_value from terminal t");
		sql.append(" left join company_info c on c.id=t.company_info_id");
		sql.append(" left join terminal_sale_org tso on t.id=tso.terminal_id");
		sql.append(" left join sale_org so on so.id=tso.sale_org_id");
		sql.append(" left join system_dict sdt on t.type=sdt.id");
		sql.append(" left join system_dict sdm on t.model= sdm.id where 1=1");
		if (companyCode != null) {
			sql.append(" and c.company_code=?");
			list.add(companyCode);
		}
		if (!ConvertUtil.isEmpty(terminalNum)) {
			sql.append(" and t.terminal_num like ?");
			list.add("%" + terminalNum + "%");
		}
		if (!ConvertUtil.isEmpty(terminalName)) {
			sql.append(" and t.terminal_name like ?");
			list.add("%" + terminalName + "%");
		}
		if (!ConvertUtil.isEmpty(sim)) {
			sql.append(" and t.sim like ?");
			list.add("%" + sim + "%");
		}
		if (saleOrgSn != null) {
			sql.append(" and so.sn=?");
			list.add(saleOrgSn);
		}
		sql.append(" order by t.create_date desc");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		Page<Map<String, Object>> getPage = getNativeDao().findPageMap(sql.toString(),
				objs,
				pageable);

		return getPage;

	}
	
	public Terminal findByTerminalNum(String terminalNum) {

		if (ConvertUtil.isEmpty(terminalNum)) {
			ExceptionUtil.throwDaoException("value is empty!");
		}
		String sql = "select * from terminal where terminal_num = ?";
		Terminal terminal = getNativeDao().findSingleManaged(sql,
				new Object[] { terminalNum },
				Terminal.class);
		return terminal;
	}
}